import { Injectable, OnModuleInit } from '@nestjs/common'
import { CompanyRepo } from '@/entities'
import { snowflake, timestampFormat } from '@/util'
import { IBodyUser, ICompany, IPagesOption } from '@/interface'
import { CoreException, CoreExceptionType } from '@/modules'

@Injectable()
export class CompanyService implements OnModuleInit {
    constructor(private readonly companyRepo: CompanyRepo) {}

    public async onModuleInit() {
        const exiting = await this.companyRepo.findOne({ companyid: '0000' })
        if (!exiting) {
            await this.companyRepo.save(
                this.companyRepo.create({
                    companyid: '0000',
                    companyName: '贝图云',
                    companyFullName: '西安贝图科技有限公司',
                    companyType: 0,
                    companyUrl: 'beituyun.com',
                    ct: timestampFormat(),
                    au: 'system',
                }),
            )
        }
    }

    /**
     * 查询企业下拉框
     */
    public async queryCompanyOption() {
        const options = await this.companyRepo.find({ companyStatus: 1 })
        const data = []
        options.map((c) => {
            data.push({
                label: c.companyName,
                value: c.companyid,
            })
        })
        return data
    }

    /**
     * 企业管理页面
     */
    public async queryCompany(option: ICompany & IPagesOption) {
        const { current = 1, pageSize = 50, companyFullName, companyUrl, companyType, companyStatus } = option
        const companyBuilder = this.companyRepo
            .createQueryBuilder('c')
            .leftJoin('project_company', 'pc', 'pc.companyid=c.companyid')
            .leftJoinAndMapMany('c.project', 'project', 'p', 'p.projectid=pc.projectid')
            .where('c.companyid>=0')
        if (companyFullName) {
            companyBuilder.andWhere('c.companyFullName like :companyFullName', {
                companyFullName: `%${companyFullName}%`,
            })
        }
        if (companyUrl) {
            companyBuilder.andWhere('c.companyUrl like :companyUrl', { companyUrl: `%${companyUrl}%` })
        }
        if (!isNaN(Number(companyType))) {
            companyBuilder.andWhere('c.companyType=:companyType', { companyType: Number(companyType) })
        }
        if (!isNaN(Number(companyStatus))) {
            companyBuilder.andWhere('c.companyStatus=:companyStatus', { companyStatus: Number(companyStatus) })
        }
        const [data, total] = await companyBuilder
            .skip((current - 1) * pageSize)
            .take(pageSize)
            .getManyAndCount()
        return {
            data,
            total,
            current,
            pageSize,
            count: data.length,
        }
    }
    public async saveCompany(option: ICompany & IBodyUser) {
        const { companyid, companyFullName, companyName, companyType, companyUrl } = option
        const au = option.__user.name
        if (companyid) {
            if (companyid === '0000') throw new CoreException(CoreExceptionType.ERROR_CORE_CONFIG_ADMIN_EDIT)
            await this.companyRepo.update(
                { companyid },
                {
                    companyFullName,
                    companyName,
                    companyUrl,
                    ed: au,
                    ut: timestampFormat(),
                },
            )
        } else {
            await this.companyRepo.save(
                this.companyRepo.create({
                    companyid: snowflake(),
                    companyName,
                    companyFullName,
                    companyUrl,
                    companyType,
                    au,
                    ct: timestampFormat(),
                }),
            )
        }
        return { message: '保存成功！' }
    }
    public async deleteCompany(option: ICompany) {
        const { companyid } = option
        if (companyid === '0000') throw new CoreException(CoreExceptionType.ERROR_CORE_CONFIG_ADMIN_DELETE)
        await this.companyRepo.delete({ companyid })
        return { message: '删除成功！' }
    }
    public async editCompanyStatus(option: { companyStatus: number; companyid: string } & IBodyUser) {
        const { companyStatus, companyid } = option
        const ed = option.__user.name
        await this.companyRepo.update(
            { companyid },
            {
                companyStatus,
                ed,
                ut: timestampFormat(),
            },
        )
        return { message: '修改成功！' }
    }
}
